﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using Controller.Class;
using Controller.Enum;
using Core.Utilities;
using Model;
using Newtonsoft.Json.Linq;

namespace Controller.Helper
{
    public class NDPrice
    {
        public static string getAllNdPriceJson()
        {
            List<tblNDPrice> nds = getAllNdPrice();
            JObject k = JObject.FromObject(new
            {
                RNdPrice = nds
            });
            return k.ToString();
        }
        public static string getLastestNdPriceItemJson()
        {
            using (DCSalePriceDataContext dataContext = new DCSalePriceDataContext())
            {
                int round = dataContext.tblNDPrices.Max(p => p.NDRound);
                var allNdPrice = from ndprice in dataContext.tblNDPrices
                                 where ndprice.NDRound == round
                                 select ndprice;

                JObject k = JObject.FromObject(new
                {
                    RNdPrice = allNdPrice
                });
                return k.ToString();
            }
        }

        public static List<tblNDPrice> getAllNdPrice()
        {
            using (DCSalePriceDataContext dataContext = new DCSalePriceDataContext())
            {
                var allNdPrice = from ndprice in dataContext.tblNDPrices
                                 where ndprice.isDisable != true orderby ndprice.NDRound descending 
                                 select ndprice ;

                return allNdPrice.ToList();
            }
        }

        public static int GetLastestRound()
        {
            using (DCSalePriceDataContext dataContext = new DCSalePriceDataContext())
            {
                int round = dataContext.tblNDPrices.Max(p => p.NDRound);
                return round;
            }
        }
        public static List<NDpriceReport> GetlastestRoundNDPric()
        {
            DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(CultureInfo.GetCultureInfo("th-TH"));
            Thread.CurrentThread.CurrentCulture = new CultureInfo("th-TH");
            using (DCSalePriceDataContext dataContext = new DCSalePriceDataContext())
            {
                int lastestRound = dataContext.tblNDPrices.Max(p => p.NDRound);
                var NDprice = (from price in dataContext.tblNDPrices

                               join detail in dataContext.tblNDPriceDetails on price.NDRound equals
                                   detail.NDRound
                               join prodDetail in dataContext.viewProductCates on detail.mprodh_grpID equals prodDetail.mprodh_grpID
                               orderby prodDetail.mprodh_sort
                               where price.NDRound == lastestRound && detail.isDisable != true 
                               select new
                               {
                                   detail.id,
                                   detail.NDRound,
                                   detail.mprodh_grpname,
                                   detail.discountPrice,
                                   detail.isDisable,
                                   prodDetail.mprodh_displayname
                               }).Select(group => new NDpriceReport
                               {
                                   id = group.id,
                                   NDRound = group.id,
                                   mprodh_grpname = group.mprodh_grpname,
                                   discountPrice = group.discountPrice,
                                   isDisable = group.isDisable,
                                   currentMonth = info.GetMonthName(DateTime.Today.Month),
                                   currentTime = DateTime.Now.ToLongDateString(),
                                   prodDisplay = group.mprodh_displayname
                               })
                              ;
                return NDprice.ToList<NDpriceReport>();

            }
        }

        public static List<NDpriceReport> GetlastestRoundNDPric(string docID)
        {
            DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(CultureInfo.GetCultureInfo("th-TH"));
            Thread.CurrentThread.CurrentCulture = new CultureInfo("th-TH");
            using (DCSalePriceDataContext dataContext = new DCSalePriceDataContext())
            {
                //int lastestRound = dataContext.tblNDPrices.Max(p => p.NDRound);
                var doc = Document.GetDocumentByID(docID);
                int lastestRound = dataContext.tblNDPrices.Where(p => p.ValidON < doc.Created).Max(n => n.NDRound);
                var NDprice = (from price in dataContext.tblNDPrices

                              join detail in dataContext.tblNDPriceDetails on price.NDRound equals
                                  detail.NDRound
                              join prodDetail in dataContext.viewProductCates on detail.mprodh_grpID equals prodDetail.mprodh_grpID
                              join prodType in dataContext.tbl_msa305_pipe_prodh_types on prodDetail.mprodh_type equals prodType.mprodh_type
                               orderby prodType.mprodh_type, prodDetail.mprodh_sort 
                              where price.NDRound == lastestRound && detail.isDisable != true
                              select new 
                                         {detail.id,
                                             detail.mprodh_grpID,
                                             detail.NDRound,
                                             detail.mprodh_grpname,
                                             detail.discountPrice,
                                             detail.isDisable,
                                             prodDetail.mprodh_displayname,
                                             prodType.mprodhtype_displayname,
                                             prodType.mprodh_type
                                         }).Select(group => new NDpriceReport
                                                                {

                                                                    id = group.id,
                                                                    NDRound = group.id,
                                                                    mprodh_grpID = group.mprodh_grpID,
                                                                    mprodh_grpname = group.mprodh_grpname,
                                                                    discountPrice = group.discountPrice,
                                                                    isDisable = group.isDisable,
                                                                    currentMonth = "วันที่ " + doc.ValidON.Value.Day + " เดือน " + info.GetMonthName(doc.ValidON.Value.Month) + " " + doc.ValidON.Value.Year + " - " + "วันที่ " + doc.ValidTO.Value.Day + " เดือน " + info.GetMonthName(doc.ValidTO.Value.Month) + " " + doc.ValidTO.Value.Year,
                                                                    //currentMonth = info.GetMonthName(DateTime.Today.Month) + " " + DateTime.Today.Year + "  วันที่ " + Month.GetFirstDayOfMonth(DateTime.Today).Day + " - " + Month.GetTheLastDayOfMonth(DateTime.Today).Day,
                                                                    //currentMonth = info.GetMonthName(DateTime.Today.Month),
                                                                    currentTime = DateTime.Now.ToLongDateString(),
                                                                    prodDisplay = group.mprodh_displayname,
                                                                    typeDisplay = group.mprodhtype_displayname,
                                                                    typeSort = group.mprodh_type
                                                                })
                              ;
                var ndPrice = NDprice.ToList<NDpriceReport>();
                //if (ndPrice.Count > 0)
                //{
                //    if (info != null)
                //    {
                //        ndPrice[0].currentMonth = info.GetMonthName(doc.Created.Month) + " " + doc.Created.Year +
                //                                  "  วันที่ " + Month.GetFirstDayOfMonth(doc.Created).Day + " - " +
                //                                  Month.GetTheLastDayOfMonth(doc.Created).Day;
                //        ndPrice[0].currentTime = doc.Created.ToLongDateString();
                //    }
                //}
                return ndPrice;

            }
        }

        //public static List<tblNDPriceDetail> GetNDPric()
        //{
        //    using (DCSalePriceDataContext dataContext = new DCSalePriceDataContext())
        //    {
        //        var NDprice = from price in dataContext.tblNDPrices

        //                      join detail in dataContext.tblNDPriceDetails on price.NDRound equals
        //                          detail.NDRound

        //                      where price.NDRound == lastestRound && detail.isDisable != true
        //                      select detail;
        //        return NDprice.ToList<tblNDPriceDetail>();

        //    }
        //}

        //public static List<ViewNDPriceMonth> GetNDPricbyMonth()
        //{
        //    using (DCSalePriceDataContext dataContext = new DCSalePriceDataContext())
        //    {
        //        var NDprice = from data in dataContext.ViewNDPriceMonths

        //                      where data.NDRound == lastestRound
        //                      select data;
        //        return NDprice.ToList<ViewNDPriceMonth>();

        //    }
       //}
        public static string GetNDPricejson(int ndRound)
        {
            using (DCSalePriceDataContext dataContext = new DCSalePriceDataContext())
            {

                int lastestRound = ndRound;
                var NDpriceLastest = from prodcate in dataContext.viewProductCates

                                     join detail in dataContext.tblNDPriceDetails on prodcate.mprodh_grpID equals detail.mprodh_grpID

                                     where detail.NDRound == lastestRound && detail.isDisable != true
                                     orderby prodcate.mprodh_sort 
                                     select new
                                     {
                                         prodcate.mprodh_grpname,
                                         detail.discountPrice,
                                         detail.NDRound,
                                         detail.NDApproverLevel1,
                                         detail.NDApproverLevel2,
                                         detail.NDApproverLevel3,
                                         detail.mprodh_grpID,

                                     };

                var NDpriceOld = from prodcate in dataContext.viewProductCates

                                 join detail in dataContext.tblNDPriceDetails on prodcate.mprodh_grpID equals detail.mprodh_grpID
                                 orderby prodcate.mprodh_sort
                                 where detail.NDRound == lastestRound - 1 && detail.isDisable != true 
                                 select new
                                 {
                                     prodcate.mprodh_grpname,
                                     prodcate.mprodh_grpID,
                                     olddiscountPrice = detail.discountPrice,

                                 };

                var NDprice = from lastestPrice in NDpriceLastest
                              join oldPrice in NDpriceOld on lastestPrice.mprodh_grpID equals oldPrice.mprodh_grpID
                                into tempOldPrice
                              from j in tempOldPrice.DefaultIfEmpty()
                              select new
                              {
                                  lastestPrice.mprodh_grpname,
                                  lastestPrice.NDRound,
                                  lastestPrice.discountPrice,
                                  olddiscountPrice = (j.olddiscountPrice == null) ? 0 : j.olddiscountPrice,
                                  lastestPrice.NDApproverLevel1,
                                  lastestPrice.NDApproverLevel2,
                                  lastestPrice.NDApproverLevel3
                              };
                JObject k = JObject.FromObject(new
                {
                    RMember = NDprice
                });

                return k.ToString();
            }
        }

        public static string GetNDPricejson()
        {
            using (DCSalePriceDataContext dataContext = new DCSalePriceDataContext())
            {
                int lastestRound = dataContext.tblNDPrices.Max(p => p.NDRound);
                var NDpriceLastest = from prodcate in dataContext.viewProductCates

                              join detail in dataContext.tblNDPriceDetails on prodcate.mprodh_grpID equals detail.mprodh_grpID
                                     orderby prodcate.mprodh_sort
                              where detail.NDRound == lastestRound && detail.isDisable != true 
                          select new
                                     {
                                         prodcate.mprodh_grpname,
                                         detail.discountPrice,
                                         detail.NDRound,
                                         detail.NDApproverLevel1,
                                         detail.NDApproverLevel2,
                                         detail.NDApproverLevel3,
                                         detail.mprodh_grpID
                                         
                                     };

                var NDpriceOld = from prodcate in dataContext.viewProductCates

                              join detail in dataContext.tblNDPriceDetails on prodcate.mprodh_grpID equals detail.mprodh_grpID
                                 orderby prodcate.mprodh_sort
                              where detail.NDRound == lastestRound -1 && detail.isDisable != true 
                              select new
                              {
                                  prodcate.mprodh_grpname,
                                  prodcate.mprodh_grpID,
                                  olddiscountPrice = detail.discountPrice,

                              };

                var NDprice = from lastestPrice in NDpriceLastest
                              join oldPrice in NDpriceOld on lastestPrice.mprodh_grpID equals oldPrice.mprodh_grpID
                              into tempOldPrice
                              from j in tempOldPrice.DefaultIfEmpty()
                              select new
                                         {
                                             lastestPrice.mprodh_grpname,
                                             lastestPrice.NDRound,
                                             lastestPrice.discountPrice,
                                             olddiscountPrice = (j.olddiscountPrice == null) ? 0 : j.olddiscountPrice,
                                             lastestPrice.NDApproverLevel1,
                                             lastestPrice.NDApproverLevel2,
                                             lastestPrice.NDApproverLevel3
                                         };
                JObject k = JObject.FromObject(new
                                                   {
                                                       RMember = NDprice
                                                   });

                return k.ToString();
            }
        }

        //private DCSalePriceDataContext dataContext = new DCSalePriceDataContext();

        public static int DocumentAction(List<tblNDPrice> ndprics, EnumAction action)
        {
            using (DCSalePriceDataContext dataContext = new DCSalePriceDataContext())
            {
                if (ndprics != null && ndprics.Count > 0)
                {
                    switch (action)
                    {
                        case EnumAction.Update:
                            try
                            {
                                foreach (tblNDPrice newndprice in ndprics)
                                {
                                    tblNDPrice oldNDprice = dataContext.tblNDPrices.Single(ndprice => ndprice.NDRound == newndprice.NDRound);
                                    oldNDprice.isDisable = newndprice.isDisable;

                                }
                                dataContext.SubmitChanges();
                                return ndprics.Count;
                            }
                            catch (Exception ex)
                            {

                                return -1;
                            }
                        case EnumAction.Insert:
                            try
                            {
                                int round = 0;
                                foreach (tblNDPrice ndprice in ndprics)
                                {
                                    dataContext.tblNDPrices.InsertOnSubmit(ndprice);
                                    dataContext.SubmitChanges();
                                    round = ndprice.NDRound;
                                }
                                //dataContext.tblNDPrices.InsertAllOnSubmit();

                                return round;

                            }
                            catch (Exception ex)
                            {
                                return -1;
                            }
                        case EnumAction.Delete:
                            try
                            {
                                var ndprice = from deletendprice in dataContext.tblNDPrices
                                              where ndprics.Contains(deletendprice)
                                              select deletendprice;
                                //dataContext.tblUsers.DeleteByPK<tblUser>(users.AsQueryable());
                                int deletedNdPrice = dataContext.tblNDPrices.DeleteBatch<tblNDPrice>(ndprice);
                                //dataContext.tblUsers.UpdateBatch<tblUser>(users1, p => new tblUser{ Email = p.DateCreated, 
                                //           UserName = "Chris Cavanagh" } );
                                //dataContext.tblUsers.DeleteAllOnSubmit(users);
                                //dataContext.SubmitChanges();
                                return deletedNdPrice;
                            }
                            catch (Exception)
                            {

                                return -1;
                            }
                    }
                }
                else
                {
                    return 0;
                }
            }
            return 0;
        }

        public static int NdPriceDetailAction(List<tblNDPriceDetail> ndpricedetails, EnumAction action)
        {
            if (ndpricedetails != null && ndpricedetails.Count > 0)
            {
                using (DCSalePriceDataContext dataContext = new DCSalePriceDataContext())
                {
                    switch (action)
                    {
                        case EnumAction.Update:
                            try
                            {
                                foreach (tblNDPriceDetail newndpricedetail in ndpricedetails)
                                {
                                    tblNDPriceDetail oldNdprice = dataContext.tblNDPriceDetails.Single(ndpricedetail => ndpricedetail.NDRound == newndpricedetail.NDRound && ndpricedetail.mprodh_grpname == newndpricedetail.mprodh_grpname);
                                    //oldNdprice.mprodh_grpname = newndpricedetail.mprodh_grpname;
                                    oldNdprice.discountPrice = newndpricedetail.discountPrice;
                                    oldNdprice.isDisable = newndpricedetail.isDisable;
                                }
                                dataContext.SubmitChanges();
                                return ndpricedetails.Count;
                            }
                            catch (Exception ex)
                            {

                                return -1;
                            }
                        case EnumAction.Insert:
                            try
                            {
                                dataContext.tblNDPriceDetails.InsertAllOnSubmit(ndpricedetails);
                                dataContext.SubmitChanges();
                                return ndpricedetails.Count;
                            }
                            catch (Exception ex)
                            {
                                return -1;
                            }
                        case EnumAction.Delete:
                            try
                            {
                                var nddetail = from deletendpricedetail in dataContext.tblNDPriceDetails
                                               where ndpricedetails.Contains(deletendpricedetail)
                                               select deletendpricedetail;
                                //dataContext.tblUsers.DeleteByPK<tblUser>(users.AsQueryable());
                                int deletedNdprice =
                                    dataContext.tblNDPriceDetails.DeleteBatch<tblNDPriceDetail>(nddetail);
                                //dataContext.tblUsers.UpdateBatch<tblUser>(users1, p => new tblUser{ Email = p.DateCreated, 
                                //           UserName = "Chris Cavanagh" } );
                                //dataContext.tblUsers.DeleteAllOnSubmit(users);
                                //dataContext.SubmitChanges();
                                return deletedNdprice;
                            }
                            catch (Exception)
                            {

                                return -1;
                            }
                    }
                }
            }
            else
            {
                return 0;
            }
            return 0;
        }


        public static int ImportPipePrice(List<WaterPipeConvert> pipePrice)
        {
            using (var dataContext = new DCSalePriceDataContext())
            {
                if (pipePrice != null && pipePrice.Count > 0)
                {

                    dataContext.ExecuteCommand("delete WaterPipeConvert");
                    dataContext.WaterPipeConverts.InsertAllOnSubmit(pipePrice);
                    dataContext.SubmitChanges();
                    return pipePrice.Count;
                    
                }
                
            }
            return 0;
        }
    }
}
